package com.lucy.common.converter;

import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.lucy.common.constant.CommonConst;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.nio.charset.StandardCharsets;

/**
 * @author kindear
 * password 加密解密
 */
@Converter
public class EncryptConverter implements AttributeConverter<String,String> {
    public EncryptConverter() {
        super();
    }

    private final String aesKey = CommonConst.AES_KEY;


    @Override
    public String convertToDatabaseColumn(String content) {
        // 密钥长度需要满足 16 位
        byte[] key = aesKey.getBytes(StandardCharsets.UTF_8);

        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

        return aes.encryptHex(content);
    }

    @Override
    public String convertToEntityAttribute(String s) {

        /*对数据进行加密，返回密文存储到数据库中**/
        //byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        try {
            byte[] key = aesKey.getBytes(StandardCharsets.UTF_8);

            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

            return aes.decryptStr(s);
        }catch (Exception e){
            return "******";
        }

    }
}
